<template>
    <div>
        <div class="container">
            <div class="handle-box">
                <el-button type="primary" @click="handleAdd">新增</el-button>
            </div>
            <el-table :data="tableData" style="width: 100%" border>
                <el-table-column label="名称" align="left">
                    <template slot-scope="scope">
                        <div @click="handleRow(scope.$index, scope.row)">
                            <span class="space" v-for="i in scope.row.level" :key="i"></span>
                            <i
                                :class="{
                                    'el-icon-caret-right': !scope.row.show,
                                    'el-icon-caret-bottom': scope.row.show
                                }"
                                v-if="scope.row.children && scope.row.children.length"
                            ></i>
                            <span class="arrow-width" v-else></span>
                            <span>{{ scope.row.name }}</span>
                        </div>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="parentName"
                         align="center"
                         label="上级部门">
        </el-table-column> -->
                <el-table-column prop="sort" align="center" label="排序"> </el-table-column>
                <el-table-column label="操作" width="180" align="center">
                    <template slot-scope="scope">
                        <el-button type="text" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                        <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 新增弹出框 -->
        <el-dialog title="新增" :close-on-click-modal="false" :visible.sync="addVisible" width="50%">
            <el-form ref="addForm" :model="addForm" label-width="auto" :rules="rules">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="addForm.name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="上级部门"
                      prop="parentName">
          <div class="block">
            <el-cascader :options="addForm.options"
                         :props="{ checkStrictly: true }"
                         clearable
                         @change="valueChange"
                         v-model="deptvalue"
                         ref="cascader"></el-cascader>
          </div>
        </el-form-item> -->

                <el-form-item label="排序">
                    <template>
                        <el-input-number
                            v-model="addForm.sort"
                            @change="handleChange"
                            :min="0"
                            :max="Infinity"
                            label="描述文字"
                        ></el-input-number>
                    </template>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveAdd">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑" :close-on-click-modal="false" :visible.sync="editVisible" width="50%">
            <el-form ref="editForm" :model="editForm" label-width="auto">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="editForm.name"></el-input>
                </el-form-item>
                <!-- <el-form-item label="上级部门"
                      prop="parentName">
          <div class="block">
            <el-cascader :options="editForm.options"
                         :props="{ checkStrictly: true }"
                         clearable
                         @change="valueChange"
                         v-model="deptvalue"
                         ref="cascader"></el-cascader>
          </div>
        </el-form-item> -->

                <el-form-item label="排序">
                    <template>
                        <el-input-number
                            v-model="editForm.sort"
                            @change="handleChange"
                            :min="0"
                            :max="Infinity"
                            label="描述文字"
                        ></el-input-number>
                    </template>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editVisible = false">取 消</el-button>
                <el-button type="primary" @click="saveEdit">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data() {
        return {
            // deptName: "",
            deptvalue: [],
            editVisible: false,
            addVisible: false,
            rules: {
                name: [{ required: true, message: '必填不能为空', trigger: 'blur' }],
                parentName: [{ required: false, message: '必填不能为空', trigger: 'blur' }]
            },
            editForm: {
                id: '',
                pid: '',
                children: [],
                name: '',
                description: '',
                sort: 0,
                createDate: null,
                parentName: null,
                options: [
                    {
                        value: '',
                        label: '',
                        children: []
                    }
                ]
            },
            addForm: {
                name: '',
                description: '',
                roles: [],
                status: 1,
                parentName: '',
                sort: 0,
                pid: '',
                options: [
                    {
                        value: '',
                        label: '',
                        children: []
                    }
                ]
            },
            tableData: [
                {
                    id: 1,
                    pid: '0',
                    name: '',
                    sort: 1,
                    parentName: null,
                    createDate: null,
                    show: false,
                    children: []
                }
            ],
            ids: []
        };
    },

    created() {
        // 获取数据
        this.getJSData();
    },
    computed: {},
    watch: {
        deptvalue() {
            if (this.$refs.cascader) {
                this.$refs.cascader.dropDownVisible = false;
            }
        }
    },

    methods: {
        async getJSData() {
            try {
                const url = '/dept/query';
                const { data: res } = await this.$http[4].get(url);
                console.log('部门管理列表：', res);
                if (res.code !== '0000') {
                    return;
                }
                function myMap(array) {
                    array.map(item => {
                        item.show = false;
                        if (item.permissions && item.permissions.length) {
                            return myMap(item.permissions);
                        }
                    });
                }
                myMap(res.data.content);
                console.log(res.data.content);
                this.tableData = res.data.content;
                this.tableData.map(item => {
                    item.show = false;
                    item.level = 0;
                    if (item.permissions && item.permissions.length) {
                        item.permissions.map(subItem => {
                            subItem.show = false;
                            subItem.level = 1;
                            if (subItem.permissions && subItem.permissions.length) {
                                subItem.permissions.map(grandsonItem => {
                                    grandsonItem.show = false;
                                    grandsonItem.level = 2;
                                });
                            }
                        });
                    }
                });
                console.log('部门管理', this.tableData);
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //     message: err.message,
                //     duration: 1500
                // });
            }
        },
        // 上级部门 根据name找到父级id 设置给子级的pid
        valueChange(value) {
            console.log(value);
            if (this.addVisible) {
                value = value[value.length - 1];
                this.addForm.parentName = value;

                function myMap(array, name) {
                    var arr = array.map(item => {
                        if (item.name === name) {
                            return item.id;
                        } else {
                            if (item.children && item.children.length) {
                                return myMap(item.children, name);
                            }
                        }
                    });
                    return arr;
                }
                var result = myMap(this.addForm.options, value);
                var str = '';
                function recursion(array) {
                    for (var item of array) {
                        if (item === undefined) {
                            continue;
                        } else if (item !== undefined && Object.prototype.toString.call(item) === '[object Array]') {
                            recursion(item);
                        } else {
                            str = item;
                        }
                    }
                }
                recursion(result);
                this.addForm.pid = str;
            } else if (this.editVisible) {
                value = value[value.length - 1];
                this.editForm.parentName = value;
                // 根据name找到父级id 设置给子级的pid
                function myMap(array, name) {
                    var arr = array.map(item => {
                        if (item.name === name) {
                            return item.id;
                        } else {
                            if (item.children && item.children.length) {
                                return myMap(item.children, name);
                            }
                        }
                    });
                    return arr;
                }
                var result = myMap(this.editForm.options, value);
                var str = '';
                function recursion(array) {
                    for (var item of array) {
                        if (item === undefined) {
                            continue;
                        } else if (item !== undefined && Object.prototype.toString.call(item) === '[object Array]') {
                            recursion(item);
                        } else {
                            str = item;
                        }
                    }
                }
                recursion(result);
                this.editForm.pid = str;
            }
        },
        // 排序
        handleChange(currentValue, oldValue) {
            // console.log(currentValue, oldValue);
            if (this.addVisible) {
                this.addForm.sort = currentValue;
            } else if (this.editVisible) {
                this.editForm.sort = currentValue;
            }
        },
        async saveAdd() {
            console.log(this.addForm);
            // 得到成功提示
            try {
                const url = '/dept/post';
                let val = {
                    name: this.addForm.name,
                    description: this.addForm.description ? this.addForm.description : '',
                    sequenceNum: this.addForm.sort,
                    roles: this.addForm.roles ? this.addForm.roles : '',
                    status: 1
                };
                const { data: res } = await this.$http[4].post(url, this.$objTostring(val), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('部门新增：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.$message.success('ok');
                this.addVisible = false;
                this.addForm = {
                    name: '',
                    description: '',
                    roles: [],
                    status: 1,
                    parentName: '',
                    sort: 0,
                    pid: '',
                    options: [
                        {
                            value: '',
                            label: '',
                            children: []
                        }
                    ]
                };
                this.getJSData();
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //     message: err.message,
                //     duration: 1500
                // });
            }
        },

        // 递归思想: 添加label属性
        addLabelAttribute(arr) {
            for (var i = 0; i < arr.length; i++) {
                if ('children' in arr[i] && arr[i].children.length !== 0) {
                    arr[i].label = arr[i].name;
                    arr[i].value = arr[i].name;
                    this.addLabelAttribute(arr[i].children);
                } else if ('children' in arr[i] && arr[i].children.length === 0) {
                    arr[i].label = arr[i].name;
                    arr[i].value = arr[i].name;
                    delete arr[i].children;
                } else if (!('children' in arr[i])) {
                    arr[i].label = arr[i].name;
                    arr[i].value = arr[i].name;
                }
            }
        },
        // 保存编辑
        async saveEdit() {
            console.log(this.editForm);
            // 得到成功提示
            try {
                const url = '/dept/update';
                let val = {
                    name: this.editForm.name,
                    deptId: this.editForm.id,
                    sequenceNum: this.editForm.sort,
                    roles: this.editForm.supportRoles,
                    description: this.editForm.description,
                    status: this.editForm.status
                };
                const { data: res } = await this.$http[4].post(url, this.$objTostring(val), {
                    headers: {
                        'Content-type': 'application/x-www-form-urlencoded'
                    }
                });
                console.log('初始化编辑菜单：', res);
                if (res.code !== '0000') {
                    return;
                }
                this.$message.success('ok');
                this.editVisible = false;

                this.getJSData();
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //     message: err.message,
                //     duration: 1500
                // });
            }
        },
        // 编辑操作
        handleEdit(index, row) {
            // console.log(index, row);
            this.idx = index;
            this.editVisible = true;

            // 初始化上级部门  editForm.options: []
            this.initParaentDept();
            // 初始化编辑表单页面
            this.initEditForm(row.id);
        },
        async initEditForm(id) {
            try {
                const url = '/dept/get';
                const { data: res } = await this.$http[4].get(url, {
                    params: {
                        deptId: id
                    }
                });
                console.log('编辑部门数据：', res);
                if (res.code !== '0000') {
                    return;
                }
                for (var key in res.data) {
                    this.editForm[key] = res.data[key];
                }

                this.deptvalue = [];
                // this.deptName = this.editForm.name;
                this.deptvalue.push(this.editForm.parentName);
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //     message: err.message,
                //     duration: 1500
                // });
            }
        },
        // 新增
        handleAdd() {
            // this.deptName = "";
            this.deptvalue = [];
            this.addVisible = true;
            // 初始化上级部门
            this.initParaentDept();
        },
        async initParaentDept() {
            try {
                const url = '/dept/query';
                const { data: res } = await this.$http[4].get(url);
                console.log('初始化上级菜单：', res);
                if (res.code !== '0000') {
                    return;
                }
                if (this.addVisible) {
                    this.addLabelAttribute(res.data.content);
                    this.addForm.options = res.data.content;
                    console.log(this.addForm.options);
                } else if (this.editVisible) {
                    this.addLabelAttribute(res.data.content);
                    this.editForm.options = res.data.content;
                }
                console.log(this.editForm);
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //     message: err.message,
                //     duration: 1500
                // });
            }
        },

        // 删除操作
        handleDelete(row) {
            this.$confirm('确定要删除吗？', '提示', {
                type: 'warning'
            })
                .then(() => {
                    this.deleteData('/dept/delete', row.id, this.getJSData);
                })
                .catch(() => {});
        },
        async deleteData(url, id, callback) {
            try {
                const { data: res } = await this.$http[4].delete(url, {
                    params: {
                        deptId: id
                    }
                });
                console.log('dele:', res);
                if (res.code !== '0000') {
                    return;
                }
                this.$message.success('操作成功');
                callback();
            } catch (err) {
                console.dir(err);
                // this.$message.error({
                //     message: err.message,
                //     duration: 1500
                // });
            }
        },
        handleRow(index, row) {
            index++;
            if (row.children && row.children.length > 0) {
                if (row.show) {
                    row.show = false;
                    var length = row.children.length;
                    function myMap(array) {
                        array.map(item => {
                            if (item.show) {
                                item.show = false;
                                length += item.children.length;
                                return myMap(item.children);
                            }
                        });
                    }
                    myMap(row.children);
                    this.tableData.splice(index, length);
                } else {
                    row.children.forEach(value => {
                        this.tableData.splice(index, 0, value);
                        index++;
                    });
                    row.show = true;
                }
            }
        }
    }
};
</script>
<style lang="scss">
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}
.table {
    width: 100%;
    font-size: 14px;
}
.red {
    color: #ff0000;
}
.mr10 {
    width: 120px;
    margin-right: 10px;
}
.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
